<?php

namespace App\Http\Controllers;

use App\Models\Comment;
use App\Models\Order;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    public function index(Request $request)
    {
        $data = Comment::with(['user','reply'])->where('goods_id', $request->input('goods_id'))->orderBy('created_at', 'desc')->paginate();
        return $this->response($data);
    }

    public function reply(Request $request){
        $data = Comment::with(['user','reply'])->where('user_id', $request->user()->id)->orderBy('created_at', 'desc')->paginate();
        return $this->response($data);
    }

    public function view($id)
    {
        $obj = Comment::find($id);
        return $this->response($obj);
    }

    public function store(Request $request, Comment $obj)
    {
        $order = Order::where('id', $request->input('order_id'))->where('user_id', $request->user()->id)->first();
        $comment = Comment::where('order_id', $request->input('order_id'))->where('user_id', $request->user()->id)->first();
        if (is_object($comment)) {
            abort(5022);
        }
        $all = $request->all();
        $obj->fill($all);
        $obj->order_id = $order->id;
        $obj->goods_id = $order->goods_id;
        $obj->user_id = $request->user()->id;
        $obj->save();
        $order->status = 4;
        $order->save();
        return $this->response($obj->id);
    }

    public function update($id, Request $request)
    {
        $obj = Comment::find($id);
        $data = $request->all();
        $obj->update($data);
        return $this->response($obj->id);
    }

    public function destroy($id)
    {
        $obj = Comment::find($id);
        $obj->delete();
        return $this->response();
    }
}
